package servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebServlet("/blog")
public class BlogServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BlogDao blogDao = new BlogDao();
        ObjectMapper objectMapper = new ObjectMapper();

        String respJson = "";
        // 1. 处理前端发来的请求，查看是否带有 query string 是否带有blogId
        String blogId = req.getParameter("blogId");
        if(blogId == null) {
            // 客户端查看博客列表页，返回所有博客
            List<Blog> blogList = blogDao.getBlogs();
            respJson = objectMapper.writeValueAsString(blogList);
        } else {
            // 客户端访问博客详情页，返回具体某一篇博客
            Blog blog = blogDao.getBlog(Integer.parseInt(blogId));
            respJson = objectMapper.writeValueAsString(blog);
        }

        // 2. 给客户端返回响应
        resp.setStatus(200);
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respJson);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        // 判断文章信息是否合法
        resp.setContentType("text/html; charset=utf8");
        if (title == null || title.length() == 0 || content == null || content.length() == 0) {
            resp.getWriter().write("文章的标题或正文为空,文章无法上传!");
            return;
        }

        // 从请求中的拿到会话
        HttpSession session = req.getSession(false);
        // 判断session 和 user对象是否存在
        if (session == null) {
            resp.getWriter().write("您当前处于未登录状态");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            // user 对象不存在,用户当前处于未登录状态
            resp.getWriter().write("您当前处于未登录状态");
            return;
        }

        // 构造 Blog 对象
        Blog blog = new Blog();
        blog.setUserId(user.getUserId());
        blog.setTitle(req.getParameter("title"));
        blog.setContent(content);

        // 将博客上传到数据库中
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        resp.sendRedirect("blog_list.html");
    }
}

